import { useWalletStore, useAccountStore, useAppStore, useGameDetailStore } from '@/store'
import { AccountShowType } from '@/types'
import { launchUrl } from '@/api/games'
import { THIRD_GAME } from '@/constants/global-key'
import { setItem } from '@/utils'
import { showError } from '@/utils'
import router from '@/router'
import { getGameDetailBySlug } from '@/api/other.ts'
const accountStore = useAccountStore()
// import { getBalance } from '@/api/wallet.ts'
const walletStore = useWalletStore()
const gameDetailStore = useGameDetailStore()
export const qlaunchUrl = async (callback?: any) => {
	const route = router.currentRoute.value
	const id = route.path?.split('/').pop()
	if (id) {
		const result = (await getGameDetailBySlug({
			slug: id
		})) as any
		gameDetailStore.setCurrentGameDetails({ ...result?.data })
		if (result?.data) {
			doGame(result?.data, callback)
		}
	}
}
const doGame = async (item: any, callback: any) => {
	try {
		if (accountStore.token) {
			const appStore = useAppStore()
			const { data } = await launchUrl({
				gameCode: item.gameCode,
				walletCurrency: walletStore.balanceCur?.currency || 0,
				gameCurrency: walletStore.balanceCur?.currency || 'USD',
				lang: appStore.lang,
				device: 'DESKTOP',
				funMode: item.funMode,
				referrer: location.href
			})
			const urlObj = new URL(data.game_url)

			const params = Object.fromEntries(urlObj.searchParams.entries())
			setItem(THIRD_GAME, params)
			callback && callback()
		} else {
			accountStore.showAccount(AccountShowType.login)
		}
	} catch (error: any) {
		console.log(error, 'error123')
		showError(error)
	}
}
